/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Client.domain;

import Client.gui.ClientWindow;
import Client.network.NetworkClient;
import Client.persistence.PictureLoader;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Ripper
 */
public class ClientDomainController 
{
    private ClientWindow cw;
    private String user;
    
    private PictureLoader picLoader;
    private ImageProcessor imageProcessor;
    private NetworkClient connection;
    private Thread connectionThread;
    
    private ClientGameSession gamesession;
    private GameLoop loop;
    private Thread gameThread;
    
    public ClientDomainController(ClientWindow window)
    {
        cw = window;
        picLoader = new PictureLoader();
        imageProcessor = new ImageProcessor(picLoader);
    }
    
    public void login(String username, String password) throws UnknownHostException
    {
        String[] info = {username, password};

        launchConnection(info);
    }
    public void register(String[] registerStuff) throws UnknownHostException
    {
        launchConnection(registerStuff);
    }
    public BufferedImage getImage(String id, Color[] colors)
    {
        return imageProcessor.createFancyImage(id, colors);
    }
    public BufferedImage getImage(int id)
    {
        return imageProcessor.makeWhitesTransparent(picLoader.getImage(id));
    }
    public BufferedImage getImage(String id)
    {
        return imageProcessor.makeWhitesTransparent(picLoader.getImage(id));
    }
    public void launchConnection(String[] info) throws UnknownHostException
    {
        if(connectionThread == null || !connectionThread.isAlive())
        {
            String ip = "127.0.0.1";
            int port = 4441;
            connection = new NetworkClient(ip, port, this, info);
            connectionThread = new Thread(connection);

            connectionThread.start();
        }
        else
        {
            displayErrorMessage("Unable to launch new connection, \nold connection still running...");
        }
    }
    
    public void loginOk(String userName)
    {
        user = userName;
        cw.loginOk(user);
    }
    public String getUsername()
    {
        return user;
    }
    public void registerOk(String userName)
    {
        loginOk(userName);
        cw.displayInfoMessage("Registration ok!");
    }
    
    public void registrationFailed(String message)
    {
        displayErrorMessage(message);
    }
    public void loginWrongPassword()
    {
        displayErrorMessage("Unable to login: wrong password.");
    }
    
    public void loginUnkownUser()
    {
        displayErrorMessage("Unable to login: unknown user.");
    }
    public void alreadyLoggedIn()
    {
        displayErrorMessage("Unable to login: already logged in.");
    }
    
    public void displayErrorMessage(String msg)
    {
        cw.displayErrorMessage(msg);
    }
    
    public void startTheGame()
    {
        gamesession = new ClientGameSession(this);
        
        loop = new GameLoop(this, gamesession);
        gameThread = new Thread(loop);
        gameThread.start();
    }
    public void shutdowngame()
    {
        loop.stopRunning();
    }
    
    public void updateWindow()
    {
        cw.updateGameScreen(gamesession);
    }
    public void tellServer(String msg)
    {
        loop.addMessageToServer(msg);
    }
    public void playerHasSpoken(String plr, String encodedMsg)
    {
        cw.playerHasSpoken(plr, encodedMsg);
    }
    public void addTextEffect(Color c, int x, int y, String txt)
    {
        cw.addTextEffect(c,x,y,txt);
    }
    
    public String askTheServer(String question)
    {
        /*connection.setOutputMessage(question);
        
        String reply = "";
        while(reply.length() < 1)
        {
            reply = connection.extractInputMessage();
        }
        
        return reply;*/
        try
        {
            String response = connection.directlyAskServer(question);
            //System.out.println("question:\n"+question+"\nanswer:\n"+response);
            return response;
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            return "";
        }
    }
    
    @Override
    public void finalize()
    {
        try
        {
            connection.stopRunning();
            try {
                super.finalize();
            } catch (Throwable ex) {
                Logger.getLogger(ClientDomainController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        catch(Exception ex) {}
    }

    public BufferedImage surroundImageWithBorder(BufferedImage image, Color selectingColor) 
    {
        return imageProcessor.surroundImageWithBorder(image, selectingColor);
    }

    public BufferedImage mirrorHorizontally(BufferedImage img) 
    {
        return imageProcessor.mirrorHorizontally(img);
    }
}
